package com.clubs.coding.Controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.clubs.coding.Service.UserService;
import com.clubs.coding.common.ApiRestResponse;
import com.clubs.coding.exception.ImoocMallException;
import com.clubs.coding.exception.ImoocMallExceptionEnum;
import com.clubs.coding.model.Vo.UserVo;
import com.clubs.coding.model.pojo.User;
import com.clubs.coding.model.request.UserReq;
import com.clubs.coding.model.request.WeChatPhone;
import com.clubs.coding.model.request.WeChatPhoneInfo;
import com.clubs.coding.utils.JwtToken;

import com.clubs.coding.utils.getWeChatPhoen;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@ResponseBody
@RequestMapping("/user")

public class UserController {
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.AppSecret}")
    private String AppSecret;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    UserService userService;
@Autowired
WeChatPhone weChatPhone;
    @PostMapping("/wx/login")
    public ApiRestResponse wxlogin(@RequestParam(value = "code", required = false) String code,
                                   @RequestParam(value = "rawData", required = false) String rawData,
                                   @RequestParam(value = "signature", required = false) String signature,
                                   @RequestParam(value = "encrypteData", required = false) String encrypteData,
                                   @RequestParam(value = "iv", required = false) String iv) {
        Map<String, Object> result = new HashMap<>();
        result.put("status", 200);
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + appid +
                "&secret=" + AppSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";//从微信拿到的code对url进行拼接
        String jsonData = restTemplate.getForObject(url, String.class);//对微信服务器发送请求
        // 签名：signature
        System.out.println(jsonData);
        JSONObject jsonObject = JSONObject.parseObject(jsonData);//转化为jsonObject对象

        JSONObject rawDataJson1 = JSONObject.parseObject(rawData);

        if (StringUtils.contains(jsonData, "errcode")) {//判断微信服务器返回的参数 看是否能登录 存在errcode这个字段则不行
            //出错了
            return ApiRestResponse.error(300, "登录失败");
        }
        String md5key = "MRONE" + DigestUtils.md5Hex(jsonData + "MRONE_WX_LOGIN");

        //校验通过 规则:WX_LOGIN_(MD5值)
//       redisKey = "WX_LOGIN" + md5key;
//       redisTemplate.opsForValue().set(redisKey, jsonData, Duration.ofDays(1));  //存到redis 1天
        String openid = jsonObject.getString("openid");
        String session_key = jsonObject.getString("session_key");
        result.put("openid", openid); //session_key和openid不应该返回到客户端
        result.put("session_key", session_key);
        String nickName = rawDataJson1.getString("nickName");
        String avatarUrl = rawDataJson1.getString("avatarUrl");
        String gender = rawDataJson1.getString("gender");
        String city = rawDataJson1.getString("city");
        String country = rawDataJson1.getString("country");
        String province = rawDataJson1.getString("province");
        result.put("nickName", nickName);
        result.put("avatarUrl", avatarUrl);
        result.put("gender", gender);
        result.put("city", city);
        result.put("country", country);
        result.put("province", province);
//        -----------生成
        String registerUser = registerUser(result);

        Map<String, Object> result1 = new HashMap<>();
        result1.put("openid", openid);
        result1.put("session_key", session_key);
        result1.put("token", registerUser);

        return ApiRestResponse.success(result1);
    }



    private String registerUser(Map<String, Object> session) {
        System.out.println(session + "xxx");
        String openid = (String) session.get("openid");

        if (openid.isEmpty()) {
            throw new ImoocMallException(ImoocMallExceptionEnum.REQUEST_PARAM_ERROR);
        }


        User userOptional = this.userService.findByOpenid(openid);

//        判断是登录还是注册
        if (userOptional != null) {
            //存在
            // TODO:返回JWT令牌

            String makeToken = JwtToken.makeToken(userOptional.getId().longValue());
            userOptional.setLastVisitTime(new Date());
            userOptional.setToken(makeToken);
            userService.updateuser(userOptional);
            return makeToken;
        }
        //不存在

        User userold = new User();
        userold.setOpenId(openid);
        userold.setCreateTime(new Date());
        userold.setLastVisitTime(new Date());
        userold.setCity((String) session.get("city"));
        userold.setNickName((String) session.get("nickName"));
        userold.setAvatarUrl((String) session.get("avatarUrl"));
        userold.setGender(Integer.parseInt((String) session.get("gender")));
        userold.setCountry((String) session.get("country"));
        userold.setProvince((String) session.get("province"));
        userService.inopenid(userold);
        User byOpenid = userService.findByOpenid(openid);//找

        // TODO:返回JWT令牌
        Long uid = byOpenid.getId().longValue();
        String token = JwtToken.makeToken(uid);
        User userold1 = new User();
        byOpenid.setToken(token);
        userService.updateuser(byOpenid);
        return token;
    }
    //获取用户个人信息
    @PostMapping("/userinfo")
    public ApiRestResponse GetUserInfor(String openid) {

        UserVo userinfo = userService.userinfo(openid);
        System.out.println(openid);
        return ApiRestResponse.success(userinfo);
    }
    //完善个人信息
    @PostMapping("/ipi")
    public ApiRestResponse ipi(@Valid @RequestBody UserReq userReq){
    userService.ipi(userReq);
    return ApiRestResponse.success();
    }
    /**
     * 用前端请求接口获取的code换取用户手机号
     * 前端需要请求的接口：https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
     * @param weChatPhone
     * @return
     */
    @PostMapping("/phone")
    public ApiRestResponse getPhone(String code) {
////        /*设置Appid和SecretKey*/
////        weChatPhone.setAppid(appid);
////        weChatPhone.setSecretKey(AppSecret);
//        // 1.请求微信接口服务，获取accessToken
//
        cn.hutool.json.JSONObject accessTokenJson = getWeChatPhoen.getAccessToken(weChatPhone.getAppid(), weChatPhone.getSecretKey());
        String accessToken = accessTokenJson.get("access_token", String.class);
        // 2.请求微信接口服务，获取用户手机号信息
        cn.hutool.json.JSONObject phoneNumberJson = getWeChatPhoen.getPhoneNumber(code, accessToken);
        WeChatPhoneInfo phoneInfo = phoneNumberJson.get("phone_info", WeChatPhoneInfo.class);
        System.out.println(phoneInfo + "xxx");

        return ApiRestResponse.success(phoneInfo.getPurePhoneNumber());

    }

//开通会员
    @PostMapping("/openmembr")
    public ApiRestResponse openMembr(String openid){
        userService.openMembr(openid);
        return ApiRestResponse.success();
    }
    @PostMapping("/swap")
    //手机号换取库中openid
    public ApiRestResponse swap(String mobile){
        String swap = userService.swap(mobile);
        return ApiRestResponse.success(swap);
    }

}
